using System;
using System.Configuration;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web;
using System.Web.Security;
using ASPNETVN.PORTAL.Components.Configuration;
using ASPNETVN.PORTAL.Components.Security;

namespace ASPNETVN.PORTAL
{
    public class Global : HttpApplication
    {
        #region DatabaseType enum

        public enum DatabaseType
        {
            MSSQL,
            Access,
            Oracle,
            MySQL,
        }

        #endregion
        
        /// <summary>
        /// Portal ID.
        /// </summary>
        /// 
        public static int PortalID = Convert.ToInt32(ConfigurationManager.AppSettings["PortalID"]);
        
        /// <summary>
        /// Application path.
        /// </summary>
        public static string ApplicationPath = ConfigurationManager.AppSettings["ApplicationPath"];

        /// <summary>
        /// Resource manager.
        /// </summary>
        public static ResourceManager RM = new ResourceManager("ASPNETVN.PORTAL.App_GlobalResources.Strings", typeof (Global).Assembly);

        protected void Application_Start(Object sender, EventArgs e)
        {
        }

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            int tabIndex = 0;
            int tabId = 1;

            // Get TabIndex from querystring
            if (Request.Params["tabindex"] != null)
            {
                tabIndex = Int32.Parse(Request.Params["tabindex"]);
            }

            // Get TabID from querystring
            if (Request.Params["tabid"] != null)
            {
                tabId = Int32.Parse(Request.Params["tabid"]);
            }

            // Build and add the Portal object to the current Context
            Context.Items.Add("Portal", new Components.Configuration.Items.Portal(tabIndex, tabId));

            // Retrieve and add the Portal DataSet to the current Context
            HttpContext.Current.Items.Add("PortalDataSet", PortalConfiguration.GetPortalDataSet());


            // Language.
            Components.Configuration.Items.Portal portal = (Components.Configuration.Items.Portal)HttpContext.Current.Items["Portal"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(portal.Language);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(portal.Language);
        }

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity) HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket = id.Ticket;

                        // Get the stored user-data, in this case, our roles.
                        string userData = ticket.UserData;
                        string[] roles = userData.Split(';');

                        PortalSecurity.CurrentUser = new PortalPrincipal(Context.User.Identity, roles);
                    }
                }
            }
            /*
            if (Request.IsAuthenticated)
            {
                string[] roles;

                // Create the roles cookie if it doesn't exist yet for this session.
                if ((Request.Cookies["portalroles"] == null) || (Request.Cookies["portalroles"].Value == ""))
                {
                    // Get roles from UserRoles table, and add to cookie
                    roles = Components.Security.User.GetRoles(PortalSecurity.CurrentUser.Identity.ID);

                    // Create a string to persist the roles
                    string roleStr = "";
                    foreach (string role in roles)
                    {
                        roleStr += role;
                        roleStr += ";";
                    }

                    // Create a cookie authentication ticket.
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1, // version
                        PortalSecurity.CurrentUser.Identity.ToString(), // user name
                        DateTime.Now, // issue time
                        DateTime.Now.AddHours(1), // expires every hour
                        false, // don't persist cookie
                        roleStr // roles
                        );

                    // Encrypt the ticket
                    string cookieStr = FormsAuthentication.Encrypt(ticket);

                    // Send the cookie to the client
                    Response.Cookies["portalroles"].Value = cookieStr;
                    Response.Cookies["portalroles"].Path = "/";
                    Response.Cookies["portalroles"].Expires = DateTime.Now.AddMinutes(1);
                }
                else
                {
                    // Get roles from roles cookie
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies["portalroles"].Value);

                    //convert the string representation of the role data into a string array
                    ArrayList userRoles = new ArrayList();

                    foreach (string role in ticket.UserData.Split(new char[] {';'}))
                    {
                        userRoles.Add(role);
                    }

                    roles = (string[]) userRoles.ToArray(typeof (string));
                }

                // Add our own custom principal to the request containing the roles in the auth ticket
                PortalSecurity.CurrentUser = new PortalPrincipal(Context.User.Identity, roles);
            }
            */
        }

        //*********************************************************************
        //
        // GetApplicationPath Method
        //
        // This method returns the correct relative path when installing
        // the portal on a root web site instead of virtual directory
        //
        //*********************************************************************
        public static string GetApplicationPath(HttpRequest request)
        {
            string path = string.Empty;
            try
            {
                if (request.ApplicationPath != "/")
                    path = request.ApplicationPath;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return path;
        }

        public static string GetMasterFile()
        {
            const string masterfile = "Office";
            Components.Configuration.Items.Portal portal = HttpContext.Current.Items["Portal"] as Components.Configuration.Items.Portal;
            if (portal != null)
            {
                if (!string.IsNullOrEmpty(portal.ActiveTab.ThemeName))
                    return portal.Layout;
            }
            return masterfile;
        }

        public static string GetThemeName()
        {
            const string themeName = "WindowsLive";
            Components.Configuration.Items.Portal portal = HttpContext.Current.Items["Portal"] as Components.Configuration.Items.Portal;
            if (portal != null)
            {
                if (!string.IsNullOrEmpty(portal.ActiveTab.ThemeName))
                    return portal.ActiveTab.ThemeName;
                return portal.DefaultTheme;
            }
            return themeName;
        }

        public static DatabaseType GetDatabaseType()
        {
            DatabaseType returnValue = DatabaseType.MSSQL;
            string dbType = ConfigurationManager.AppSettings["DatabaseType"];

            switch (dbType)
            {
                case "MSSQL":
                    returnValue = DatabaseType.MSSQL;
                    break;
                case "Access":
                    returnValue = DatabaseType.Access;
                    break;
                case "Oracle":
                    returnValue = DatabaseType.Oracle;
                    break;
                case "MySQL":
                    returnValue = DatabaseType.MySQL;
                    break;
            }
            return returnValue;
        }
    }
}